package com.promise.jokerdream.work

import com.promise.jokerdream.config.user.UserConfig
import com.promise.jokerdream.manager.ExecutionHistoryManager
import com.promise.jokerdream.repository.PhoneGameApi
import com.promise.jokerdream.utils.AppContext
import com.promise.jokerdream.work.manager.CommonWorkManager

/**
 * 一键代玩执行器
 * 负责执行一键代玩的业务逻辑
 */
class OneClickPlayExecutor {
    
    private val workManager = CommonWorkManager.getInstance()
    private val historyManager by lazy { ExecutionHistoryManager.getInstance(AppContext.get()) }
    private val phoneGameApi = PhoneGameApi.getInstance()
    
    /**
     * 执行一键代玩
     * @param userId 用户ID
     * @param userConfig 用户配置
     * @return 执行结果
     */
    suspend fun executeOneClickPlay(userId: String, userConfig: UserConfig): OneClickPlayResult {
        return try {
            // 创建工作列表
            val allWorks = WorkFactory.createWorks(userId, userConfig)
            
            if (allWorks.isEmpty()) {
                return OneClickPlayResult.Success("没有启用的工作项")
            }

            // 查询最新活动信息
            val latestActResult = phoneGameApi.queryLatestActData()
            val availableActList = latestActResult.getOrNull()?.actList ?: emptyList()
            
            // 过滤活动类工作
            val filteredWorks = allWorks.filter { work ->
                if (work.isActWork) {
                    // 如果活动列表为空，不过滤任何活动类工作
                    if (availableActList.isEmpty()) {
                        true
                    } else {
                        // 检查活动类工作是否在活动列表中
                        val isActAvailable = availableActList.any { actName ->
                            actName.contains(work.name, ignoreCase = true)
                        }
                        isActAvailable
                    }
                } else {
                    true
                }
            }

            if (filteredWorks.isEmpty()) {
                return OneClickPlayResult.Success("没有可执行的工作项")
            }

            // 记录执行历史
            historyManager.addHistory("小恶魔", "开始执行一键代玩，共 ${filteredWorks.size} 个工作项")
            
            // 添加过滤后的工作到管理器
            workManager.addWorks(filteredWorks)
            
            OneClickPlayResult.Success("成功添加 ${filteredWorks.size} 个工作项到执行队列")
            
        } catch (e: Exception) {
            e.printStackTrace()
            historyManager.addHistory("小恶魔", "一键代玩执行失败: ${e.message}")
            OneClickPlayResult.Failure(e, e.message ?: "未知错误")
        }
    }
    
    /**
     * 执行单个工作
     * @param work 要执行的工作
     * @return 执行结果
     */
    fun executeSingleWork(work: IWork): OneClickPlayResult {
        return try {
            // 添加单个工作到管理器
            workManager.addWork(work)
            
            OneClickPlayResult.Success("成功添加工作「${work.name}」到执行队列")
            
        } catch (e: Exception) {
            e.printStackTrace()
            historyManager.addHistory("小恶魔", "执行工作「${work.name}」失败: ${e.message}")
            OneClickPlayResult.Failure(e, e.message ?: "未知错误")
        }
    }
}

/**
 * 一键代玩执行结果
 */
sealed class OneClickPlayResult {
    data class Success(val message: String) : OneClickPlayResult()
    data class Failure(val exception: Throwable, val message: String) : OneClickPlayResult()
}
